/* Copyright 2009 Palm, Inc.  All rights reserved. */

var fdnBookList = [];
var fdn_capacity = -1;
var fdn_used;
var fdn_name_length;
var fdn_number_length;
var gsm = false;

var FdnAssistant = Class.create({

    initialize: function(){
        this.getMaxCapacity();
        this.fdnObject = new Object();
    },
    
    setup: function(){
    
        this.fdnBookModel = {
            listTemplateAttr: {
            },
            items: fdnBookList
        };
        
        this.controller.setupWidget('fdnBookList', {
            itemTemplate: 'fdn/listitem',
            listTemplate: 'fdn/listcontainer',
            addItemLabel: $L('Add an entry...')
        }, this.fdnBookModel);
        
        $('fdnBookList').observe('mojo-list-tap', this.listClickHandler.bindAsEventListener(this));
        $('fdnBookList').observe('mojo-list-add', this.listAddHandler.bindAsEventListener(this));
        
		// App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
            items: [Mojo.Menu.editItem, {label:$L('Help'), command:Mojo.Menu.helpCmd}]
        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);
        
    },
    
    activate: function(){
        this.updateListModel();
    },
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if (event.command == Mojo.Menu.helpCmd) {
				var r = new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/phone/phone_prefs/index.html'}}});
			}
		}
	},	
    
    listClickHandler: function(event){
        if (event.item) {
            this.fdnObject = event.item;
            this.showSecurityBox();
        }
        
    },
    
    
    
    listAddHandler: function(){
        if (fdn_capacity == -1) { 
            Mojo.Controller.errorDialog($L("Phonebook unavailable. Please try again."));
        } else { 
            if (fdnBookList.length < fdn_capacity) {
                this.fdnObject = null;
                this.showSecurityBox();
            }
            else {
                Mojo.Controller.errorDialog($L("Fixed dialing phonebook capacity exceeded"));
            }
		}
    },
    
    loadSimBook: function(){
		this.simbookReadReq = TelephonyService.simbookRead(fdn_capacity-1, this.simbookReadCallback.bind(this));
    },
    
	simbookReadCallback: function(payload){
		if (payload && payload.returnValue === true) {
			if (payload.extended.entries) {
				var arr = payload.extended.entries;
				fdnBookList.clear();
				for (var i = 0; i < arr.length; i++) {
					if (arr[i].name || arr[i].number) {
						fdnBookList.push({
							name: arr[i].name || arr[i].number,
							number: arr[i].number,
							index: arr[i].index,
							type: 'fdn'
						});
					}
				}
				fdnBookList.sort(this.sortByName.bind(this));
				this.updateListModel();
			}
			$('fdn_progress').hide();
		}
		else if( payload && payload.returnValue === false){
        	Mojo.Controller.errorDialog(payload.errorText);
            $('fdn_progress').hide();
		}		
	},
	sortByName: function(a, b){
		var arr = [a.name.toLowerCase(), b.name.toLowerCase()];
		arr.sort();
		if(arr[0] == a.name.toLowerCase()) {		
			return -1;
		} else {
			return 1;
		}
	},
    updateListModel: function(){
		fdnBookList.sort(this.sortByName.bind(this));
        this.controller.modelChanged(this.fdnBookModel, this);
    },
    
    showSecurityBox: function(){
        this.pin2StatusReq = TelephonyService.pin2Status(this.showPin2OrPuk2Box.bind(this));
	},

	showPin2OrPuk2Box: function(payload){
		if (payload && payload.returnValue){
			if (payload.extended.pukrequired){
				PrefSetter.displayPuk2Lock();
			}
			else{
				this.showPin2Box();				
			}
		}
		else{
			this.showPin2Box();				
		}
	},

    showPin2Box: function(){
		var pincodeArgs = {
			title: [$L("Enter PIN2")],
			pinPages: 1,
			hasCallback: true,
			callbackHandler: this.pinVerify.bind(this)
		};
		this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			},pincodeArgs);
    },
    
    pinVerify: function(callback,pin){
		this.pin2VerifyReq = TelephonyService.pin2Verify(pin[0], this.pin2VerifyCallback.bind(this, callback));        
    },
    
	pin2VerifyCallback:function(callback, payload){
		if(payload && payload.returnValue === true){
			callback(true);
            Mojo.Controller.stageController.pushScene('fdnedit', this.fdnObject);
		}
		else if(payload && payload.returnValue === false){
	        if (payload.errorCode == 3) {
				callback(true, "no dial");
				PrefSetter.displayPuk2Lock();
			}
			else {
				if (Messages.pin2VerifyError[payload.errorCode] !== undefined) {
					payload.errorText = Messages.pin2VerifyError[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.pin2VerifyError[Messages.defaultErrorIndex].toString();
				}

				if (payload.extended && payload.extended.attemptsRemaining) {
					var message = Mojo.Format.formatChoice(
						payload.extended.attemptsRemaining, 
						$L("1##{error} 1 try remaining|1>##{error} #{count} tries remaining"), { 
							"count": payload.extended.attemptsRemaining,
							"error": payload.errorText
						});
					callback(false, message);
				}
				else {
					callback(false, payload.errorText);
				}
			}
		}	
	},
	
    getMaxCapacity: function(){
		this.simbookCapacityQueryReq = TelephonyService.simbookCapacityQuery(this.getMaxCapacityCallback.bind(this));
	},
	
	getMaxCapacityCallback: function(payload){
		if (payload && payload.returnValue === true) {//success
			fdn_capacity = payload.extended.capacity;
			fdn_used = payload.extended.used;
			this.getMaxLength();
		}  
      	else if(payload && payload.returnValue === false){//failure
	        $('fdn_progress').hide();
        }
    },
    
    getMaxLength: function(){
   		this.simbookEntryMaxLengthQueryReq = TelephonyService.simbookEntryMaxLengthQuery(this.getMaxLengthCallback.bind(this));
	},
	
	getMaxLengthCallback: function(payload){    
		if(payload && payload.returnValue === true){
		    fdn_name_length = payload.extended.name;
            fdn_number_length = payload.extended.number;
            this.loadSimBook();
        }
		else if(payload && payload.returnValue === false){
		    $('fdn_progress').hide();
        }
    }
    
});





